<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Inventory;

use App\Models\Basics\SysArea;
use App\Models\Inventory\AreaCn;
use App\Models\Inventory\Transfer;
use App\Models\Inventory\TransferA;
use App\Models\Stocking\StockingSku;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
class TransferAAjax {

    public function transfer($param){
        try{
            $iAreaId = $param['iarea_id'];
            $detail = $param['detail'];
            $count = 0;
            $userId = Admin::user()->id;
            $areaTEMPId = SysArea::getSysAreaIdByArea('TEMP');
            foreach($detail as $item){
                $oAreaId = $item['oarea_id'];
                if($iAreaId == $oAreaId)continue;
                $id = $item['id'];
                DB::beginTransaction();

                //站点挪用
                $transferA = TransferA::query()->lockForUpdate()->find($id);
                $num = $item['transfer_num'];
                if($num > $transferA->instant){
                    DB::rollBack();
                    continue;
                }
                $transferA->instant -= $num;
                $flag1 = $transferA->save();
                if(!$flag1){
                    DB::rollBack();
                    continue;
                }
                if($oAreaId == $areaTEMPId){
                    $status = 2;
                    $areaCn = AreaCn::query()->firstOrNew(['area_id' => $iAreaId,'psku_id' => $transferA->psku_id]);
                    $areaCn->instant += $num;
                    $flag2 = $areaCn->save();
                    if(!$flag2){
                        DB::rollBack();
                    }
                }else{
                    $status = 1;
                }
                //挪用记录
                $transfer = Transfer::query()->create([
                    'psku_id' => $transferA->psku_id,
                    'iuser_id' => $userId,
                    'iarea_id' => $iAreaId,
                    'oarea_id' => $oAreaId,
                    'transfer_num' => $num,
                    'status' => $status,
                ]);
                if($transfer){
                    if($oAreaId == $areaTEMPId){
                        StockingSku::upCnInstant($iAreaId.'_'.$transferA->psku_id);
                    }else{
                        StockingSku::upCnInstant($oAreaId.'_'.$transferA->psku_id);
                    }
                    $count++;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            return response()->json(['status' => true, 'message' => '挪用成功'.$count.'条记录']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误']);
        }
    }

}
